const express = require('express')
const shell = require('shelljs')
const fs = require('fs')
const join = require('path').join
const router = express.Router()

router.post('/shell', (req, res, next) => {
  let cmd = req.body.cmd
  fs.writeFile(join(__dirname, './shell.sh'), cmd, (err) => {
    if (err) return res.json({err})
    let child = shell.exec(cmd, { async: true })
    let txt = ''
    child.stdout.on('data', function (data) {
      /* ... do something with data ... */
      console.log('stdout:', data)
      txt = txt + data + '\n'
      fs.writeFile(join(__dirname, './shell.txt'), txt)
    })
    child.stderr.on('data', function (data) {
      /* ... do something with data ... */
      txt = txt + data + '\n'
      fs.writeFile(join(__dirname, './shell.txt'), txt)
    })
    shell.exec('sh ' + join(__dirname, './shell.sh'), (code, stdout, stderr) => {
      let html = stdout.replace('\n', '<br>')
      let result = ['shell: ' + cmd + '\n']
      result = result.concat(stdout.split('\n') || [])
      res.status(200).json({
        code, html, stderr, result
      })
    })
  })
})
module.exports = router
